<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\common\model;

use app\common\model\Goods as GoodsModel;
use app\common\model\Product as ProductM;
use app\common\model\Project as ProjectM;
use app\common\model\ViperUser as ViperUserM;
use think\Db;
use think\Model as ThinkModel;
/**
 *  购物车 模型
**/
class Cart extends ThinkModel
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'qt_cart';
    protected $pk = 'id';
    protected $autoWriteTimestamp = true;

    //接口主要查询的字段
    protected $apiField = '';
    /** ++++++++++++++++++++++++++++++++   API 接口调用下方函数    +++++++++++++++++++++++++++++++++++++++  **/

    /**
     *  单商品加入购物车
     * @param   int  $room_id     房间id
     * @param   int  $user_id     用户ID
     * @param   int  $store_id    门店ID
     * @param   int  $p_id        项目ID | 商品ID
     * @param   int  $cart_type   购物车类型: 1=门店项目  2=门店商品
     * @param   int  $num         购买数量
     * @param   int  $num_type    数量类型:   1=累加  2=覆盖
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add($room_id,$user_id,$store_id,$p_id,$cart_type,$num,$num_type)
    {
        $result = ['status'=>false,'msg'=>'','data'=>[]];

        switch ($cart_type)
        {
            //门店项目
            case 1:
                $info               =  ProjectM::where(['id'=>$p_id])->find();
                $no_msg             =  '项目不存在';
                $no_status_msg      =  '项目已下架';
                break;

            //门店商品
            case 2:
                $info =  Db::name('qt_goods')->where(['id'=>$p_id])->find();

                $no_msg             =  '商品不存在';
                $no_status_msg      =  '商品已下架';
                break;
        }

        if(!$info) {
            $result['msg'] = $no_msg;
            return $result;
        }

        if($info['status'] != 1) {
            $result['msg'] = $no_status_msg;
            return $result;
        }

        //查询商品是否已存在于购物车
        $where[] = ['uv_id','eq',$user_id];
        $where[] = ['store_id','eq',$store_id];
        $where[] = ['p_id','eq',$p_id];
        $where[] = ['cart_type','eq',$cart_type];
        $where[] = ['room_id','eq',$room_id];
        $cartInfo = $this->where($where)->find();

        if($cartInfo){
            if($num_type == 1){
                $cartInfo->num = $cartInfo['num'] + $num;
            }else{
                $cartInfo->num = $num;
            }
            $cartInfo->save();
            $cart_id = $cartInfo->id;
        }else{
            //门店商品 因有库存的存在
            //if($cart_type == 2) {
            //    //可以购买的数量
            //    $canBuyNum = $info['stock'];
            //
            //    if($num > $canBuyNum){
            //        $result['msg'] = '该商品库存不足';
            //        return $result;
            //    }
            //}

            $add['uv_id']       = $user_id;
            $add['store_id']    = $store_id;
            $add['cart_type']   = $cart_type;
            $add['p_id']        = $p_id;
            $add['room_id']        = $room_id;
            $add['num']         = $num;

            $cart_id = $this->insertGetId($add);
        }

        $result['status']   = true;
        $result['msg']      = '加入成功';
        $result['data']     = $cart_id;
        return $result;

    }


    /**
     *  详情 数据
     * @param   int  $room_id       房间id
     * @param   int  $user_id       用户ID
     * @param   int  $store_id      门店ID
     * @param   int  $cart_type     类型: 1=门店项目  2=门店商品
     * @param   int  $ids           购物车ID
     * @return  array|bool|mixed|string
     **/
    public function info($room_id,$user_id,$store_id,$cart_type,$ids)
    {
        $result   = [
            'status' => false,
            'data'   => [
                'user_id'        => $user_id,
                'store_id'       => $store_id,
                'total_nums'     => 0,                  //购物车共多少件宝贝
                'total_money'     => 0,                  //购物车共多少件宝贝
                'select_nums'    => 0,                  //结算页 共计 多少件
                'list'           => [],
                'goods_amount'   => 0,                  //商品总金额
                'order_amount'   => 0,                  //总金额
                'user_money'     => 0,                  //用户账户可用余额
                'params'         => [],                 //其他参数
            ],
            'msg'    => ""
        ];

        $cartList = $this->lists($room_id,$user_id,$store_id,$cart_type,$ids);

        if(!$cartList['status']){
            $result['msg'] = $cartList['msg'];
            return $result;
        }else{
            //如果购物车是空的就不继续下面的计算操作,直接返回
            $result['data']['list']         = $cartList['data']['list'];
            $result['data']['total_nums']   = $cartList['data']['total_nums'];
            if(count($result['data']['list']) == 0){
                $result['status'] = true;
                return $result;
            }
        }

        //计算金额
        foreach ($result['data']['list'] as $k => $v) {
            //单条商品总价
            $result['data']['list'][$k]['amount'] = bcmul($v['num'], $v['goodsInfo']['goods_price'], 2);
            $result['data']['total_money'] = $result['data']['total_money'] + bcmul($v['num'], $v['goodsInfo']['goods_price'], 2);
            //结算页选中的购物车商品进行计算订单总金额
            if ($v['is_select']) {
                //选中商品共多少件)
                $result['data']['select_nums'] = bcadd($result['data']['select_nums'], $result['data']['list'][$k]['num']);

                //订单总商品价格
                $result['data']['goods_amount'] = bcadd($result['data']['goods_amount'], $result['data']['list'][$k]['amount'], 2);

                //订单总价格
                $result['data']['order_amount'] = bcadd($result['data']['order_amount'], $result['data']['list'][$k]['amount'], 2);
            }
        }


        //$result['data']['user_money'] = UserM::where(['user_id'=>$user_id])->value('user_money');

        $result['status'] = true;
        return $result;
    }


    /**
     *  结算页信息
     *
     * @param $room_id    房间id
     * @param $user_id    用户id
     * @param $store_id   门店id
     * @param $cart_type  类型
     * @param $ids        商品 项目id
     * @return array
     */
    public function outInfo($room_id,$user_id,$store_id,$cart_type,$ids)
    {
        $result   = [
            'status' => false,
            'data'   => [
                'user_id'        => $user_id,
                'list'           => [],
                'goods_amount'   => 0,                  //商品总金额
                'order_amount'   => 0,                  //订单实付金额
                'content'        => '',                 //订单备注
                'params'         => [],                 //其他参数
            ],
            'msg'    => ""
        ];

        $cartList = $this->lists($room_id,$user_id,$store_id,$cart_type,$ids);

        if(!$cartList['status']){
            $result['msg'] = $cartList['msg'];
            return $result;
        }else{
            //如果购物车是空的就不继续下面的计算操作,直接返回
            $result['data']['list']         = $cartList['data']['list'];
            $result['data']['total_nums']   = $cartList['data']['total_nums'];
            $result['data']['select_nums']   = $cartList['data']['select_nums'];
            if(count($result['data']['list']) == 0){
                $result['status'] = false;
                $result['msg'] = "下单失败";
                return $result;
            }
        }



        //计算金额
        foreach ($result['data']['list'] as $k => $v) {
            //单条实付金额
            $amount                   = bcmul($v['num'], $v['goodsInfo']['goods_price'], 2);

            //订单总商品金额
            $result['data']['goods_amount'] = bcadd($result['data']['goods_amount'], $amount, 2);

            //订单实付金额
            $result['data']['order_amount'] = bcadd($result['data']['order_amount'], $amount, 2);

        }

        $result['status'] = true;
        return $result;
    }



    /**
     * 获取购物车列表
     * @param int       $room_id        房间id
     * @param int       $user_id        用户id
     * @param int       $store_id       门店id
     * @param int       $cart_type      类型:  1=门店项目  2=门店商品
     * @param string    $ids            购物车ID
     * @return array
     */
    public function lists($room_id,$user_id,$store_id,$cart_type, $ids)
    {
        $result = ['status'=>false,'msg'=>'','data'=>[
            'select_nums'=>0,
            'total_nums'=>0,
            'total_money'=>0,
            'list'=>[]
        ]];

        $where[]    = ['uv_id', 'eq', $user_id];
        $where[]    = ['store_id', 'eq', $store_id];
        $where[]    = ['room_id', 'eq', $room_id];
        $where[]    = ['cart_type', 'eq', $cart_type];

        if (!empty($ids)) {
            $where[]    = ['id', 'eq', $ids];
        }

        $list    = $this->where($where)->select();
        if (!$list->isEmpty()) {
            $list = $list->toArray();
            $result['data']['total_nums'] = count($list);
        }

        foreach ($list as $k => $v) {

            $result['data']['select_nums'] = bcadd($result['data']['select_nums'],$v['num'],0);

            switch ($v['cart_type'])
            {
                //门店项目
                case 1:
                    $info               =  ProjectM::where(['id'=>$v['p_id']])->find();

                    if(!$info || $info['status'] != 1)
                    {
                        unset($list[$k]);
                        continue 2;
                    }

                    $images = get_album_array_path($info['images']);
                    //取第一个主图
                    $img    = !empty($images) ?  $images[0]: "";

                    //组合 商品信息
                    $list[$k]['goodsInfo'] = [
                        'id'                    =>  $info['id'],
                        'goods_name'            =>  $info['name'],
                        'goods_img'             =>  get_img_path($img),
                        'goods_price'           =>  $info['price'],
                    ];
                    break;
                //门店商品
                case 2:
                    $info               =  ProductM::where(['id'=>$v['p_id']])->find();

                    if(!$info || $info['status'] != 1)
                    {
                        unset($list[$k]);
                        continue 2;
                    }

                    //组合 商品信息
                    $list[$k]['goodsInfo'] = [
                        'id'                    =>  $info['id'],
                        'goods_name'            =>  $info['name'],
                        'goods_img'             =>  get_img_path($info['img']),
                        'goods_price'           =>  $info['price'],
                    ];
                    break;
            }
            //再此设置选中字段,便于之后的处理
            $array_ids = explode(',', $ids);
            if (in_array($v['id'], $array_ids)) {
                $list[$k]['is_select'] = true;
            } else {
                $list[$k]['is_select'] = false;
            }
        }

        $result['data']['list']   = $list;
        $result['status'] = true;
        return $result;
    }



    /**
     *  设置购物车 数量
     * @param   int     $room_id        房间id
     * @param   int     $user_id        用户ID
     * @param   int     $store_id       门店ID
     * @param   int     $id             购物车ID
     * @param   int     $num           数量
     * @return  array|bool|mixed|string
    **/
    public function setNums($room_id,$user_id,$store_id, $id, $num)
    {

        $where[] = ['id','eq',$id];
        $where[] = ['store_id','eq',$store_id];
        $where[] = ['uv_id','eq',$user_id];
        $where[] = ['room_id','eq',$room_id];
        $res = $this->where($where)->update(['num'=>$num]);
        return $res;
    }




    /**
     *  清空购物车
     * @param   int     $room_id        房间id
     * @param   int     $user_id     用户ID
     * @param   int     $store_id     门店ID
     * @param   string  $ids         购物车ID
     * @return bool
     * @throws \Exception
     */
    public function del($room_id,$user_id,$store_id,$ids = "")
    {
        $where[] = ['uv_id','eq',$user_id];
        $where[] = ['store_id','eq',$store_id];
        $where[] = ['room_id','eq',$room_id];
        if($ids != ""){
            $where[] = ['id','in',$ids];
        }
        $result = $this->where($where)->delete();
        return $result;
    }




}